import axios from 'axios'
import store from '@/store'
import router from '../router/index'

const ajax = axios.create({
  baseURL: 'http://toutiao.itheima.net'
})
// 请求拦截器

ajax.interceptors.request.use(config => {
  // console.log(config)
  if (store.state.token) {
    config.headers.Authorization = `Bearer ${store.state.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
ajax.interceptors.response.use(resp => {
  return resp.data
}, error => {
  // console.dir(error)
  if (error.response.status === 401) {
    store.commit('settoken', '')
    // console.log(router)
    router.replace({
      path: '/login?from=' + router.currentRoute.path
    })
  }
  return Promise.reject(error)
})

export default ajax
